package com.hdd.art.biz.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdd.art.biz.login.dto.WXRegisterRequest;
import com.hdd.art.biz.member.entity.Member;
import com.hdd.art.biz.member.mapper.MemberMapper;
import com.hdd.art.biz.show.entity.ArtShow;
import com.hdd.art.biz.show.service.ArtShowService;
import com.hdd.art.biz.show.service.MemberArtService;
import com.hdd.art.dto.AppResponse;
import com.hdd.art.utils.DateUtil;
import com.hdd.art.utils.IdUtils;
import com.hdd.art.utils.JsonUtil;
import com.hdd.art.utils.RedisUtil;
import com.hdd.art.utils.http.HttpClient;
import com.hdd.art.utils.http.OkHttpResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 作者： fangzehua
 * 时间： 2021/6/19 15:18
 *
 * @Version: 1.0
 * @Desc 类描述信息
 */
@Service
@Slf4j
public class RegisterServiceImpl implements com.hdd.art.biz.login.service.impl.RegisterService {


    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;


    @Autowired
    private ArtShowService artShowService;
    @Autowired
    private MemberArtService memberArtService;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MemberMapper memberMapper;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Override
    public AppResponse register(WXRegisterRequest request) {

        AppResponse response = new AppResponse();
        if(StringUtils.isEmpty(request.getOpenid())){
            response.setMessage("授权失败,请重试");
            response.setCode(-1000);
            return response;
        }

        //获了用户信息
        Member member = null;
        String userId = null;
        //通过unionId查询,判断用户是否为新用户,如果为新用户创建用户,返回用户信息,如果是老用户直接返回用户信息
        if (member == null || member.getId() == null) {
            member = new Member();
            userId = IdUtils.getUUID();
            member.setUserId(userId);
            member.setXcxOpenid(request.getOpenid());
            member.setUnionId(request.getUnionid());
            member.setNickname(request.getNickName());
            member.setPaintingNum("100");
            member.setUsername(request.getNickName());
            member.setInvented("F");
            member.setType(0);

            if(!StringUtils.isEmpty(request.getArtId())){
                memberArtService.insert(userId,request.getArtId()+"");
            }
            member.setInvitation(request.getUserCode());
            member.setPassword(passwordEncoder.encode("123456"));
            member.setSecondTime(DateUtil.getNowTimeStr());
            member.setLastTime(DateUtil.getNowTimeStr());
            String city = request.getCity();
            if (city != null && !"".equals(city)) {
                member.setCity(request.getCity());
            }else {
                member.setCity(null);
            }
            String province = request.getProvince();
            if (province != null && !"".equals(province)) {
                member.setProvince(request.getProvince());
            }else {
                member.setProvince(null);
            }
            member.setSex(request.getGender());
            //将头像保存到本地
//			String avatarUrl = WxImageUtil.saveImageUrl(filesPath, (String) userMap.get("avatarUrl"));
            //TODO  头像要上传下

            member.setHeadImgUrl(request.getAvatarUrl());
            member.setStatus(1);
            member.setTrustType(1);
            member.setIsReal("F");
            memberMapper.insert(member);

            redisUtil.set("sessionKey:"+member.getUserId(),request.getSessionKey().toString());
            // memberBackupsService.insetMember(member);


        } else if (null == member.getXcxOpenid() || "".equals(member.getXcxOpenid())) {//当用户已经关注公众号时
            member.setXcxOpenid(request.getOpenid());
            memberMapper.insert(member);

        }
        response.setItem(userId);
        return response;
    }


    @Override
    public AppResponse getOpenId(WXRegisterRequest request) {
        AppResponse res = new AppResponse();
        log.info(appid+"===="+secret);
        //获了用户信息
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + request.getOpenCode() + "&grant_type=authorization_code";
        log.info(url);
        Member member = null;
        QueryWrapper<Member> wrapper = new QueryWrapper();
        OkHttpResponse<String> response = HttpClient.doGet(url);
        Map<String, Object> dataMap = JsonUtil.toMap(response.getData());
        if (dataMap.containsKey("unionid")) {
            wrapper.eq("union_id",dataMap.get("unionid"));
            member = memberMapper.selectOne(wrapper);
        }else if(dataMap.containsKey("openid")){
            wrapper.eq("xcx_openid",dataMap.get("openid"));
            member = memberMapper.selectOne(wrapper);
        }
        if(member==null){
            res.setCode(201);
            res.setItem(dataMap);
            return res;
        }
        res.setCode(200);
        //修改最后登录时间
        member.setLastTime(getTime());
        memberMapper.updateById(member);
        res.setItem(member.getUserId());
        if(dataMap!=null){
            redisUtil.set("sessionKey:"+member.getUserId(),dataMap.get("session_key").toString());
        }
        return res;
    }


    public String getTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        return df.format(new Date());
    }

}